package com.anji.plus.gaea.security.plus.modules.org.controller;

import com.anji.plus.gaea.annotation.AccessKey;
import com.anji.plus.gaea.annotation.Permission;
import com.anji.plus.gaea.annotation.log.GaeaAuditLog;
import com.anji.plus.gaea.bean.KeyValue;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.bean.TreeNode;
import com.anji.plus.gaea.curd.controller.GaeaBaseController;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anji.plus.gaea.security.plus.modules.org.controller.dto.GaeaOrgDTO;
import com.anji.plus.gaea.security.plus.modules.org.controller.param.GaeaOrgParam;
import com.anji.plus.gaea.security.plus.modules.org.dao.entity.GaeaOrg;
import com.anji.plus.gaea.security.plus.modules.org.service.GaeaOrgService;
import com.anji.plus.gaea.security.plus.modules.user.service.GaeaUserService;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anji.plus.gaea.utils.GaeaUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 组织(GaeaOrg)实体类
 *
 * @author lr
 * @since 2021-02-02 13:37:33
 */
@RestController
@RequestMapping("/org")
@Api(value = "/org", tags = "组织")
@Permission(code = "org", name = "组织")
public class GaeaOrgController extends GaeaBaseController<GaeaOrgParam, GaeaOrg, GaeaOrgDTO> {

    @Autowired
    private GaeaOrgService gaeaOrgService;

    @Autowired
    private GaeaUserService gaeaUserService;

    @Override
    public GaeaBaseService<GaeaOrgParam, GaeaOrg> getService() {
        return gaeaOrgService;
    }

    @Override
    public GaeaOrg getEntity() {
        return new GaeaOrg();
    }

    @Override
    public GaeaOrgDTO getDTO() {
        return new GaeaOrgDTO();
    }

    /**
     * 查询所有可用的机构信息
     *
     * @return
     */
    @GetMapping("/queryAllOrg")
    public ResponseBean queryAllOrg() {
        return responseSuccessWithData(gaeaOrgService.queryAllOrg(null));
    }

    @GetMapping("/orgSelect")
    public ResponseBean orgSelect(GaeaOrgParam gaeaOrgParam){
        List<GaeaOrg> orgList=gaeaOrgService.queryAllOrg(gaeaOrgParam);
        List<KeyValue> data=null;
        if(!CollectionUtils.isEmpty(orgList)){
            data=orgList.stream().map(e->{
                KeyValue keyValue=new KeyValue();
                keyValue.setId(e.getOrgCode());
                keyValue.setText(e.getOrgName());
                return keyValue;
            }).collect(Collectors.toList());
        }
        return responseSuccessWithData(data);
    }

    /**
     * 组织树
     * @return
     */
    @GetMapping("/tree")
    public ResponseBean orgTree() {
        return responseSuccessWithData(gaeaOrgService.tree(false));
    }


    /**
     * 机构角色树
     * @return
     */
    @GetMapping("/role/tree")
    public ResponseBean orgRoleTreeSelected() {

        List<TreeNode> tree = gaeaOrgService.tree(true);
        return responseSuccessWithData(tree);
    }

    /**
     * 角色机构分配树
     * @return
     */
    @GetMapping("/user/role/tree/{username}")
    public ResponseBean orgRoleTree(@PathVariable("username") String username) {

        List<TreeNode> tree = gaeaOrgService.tree(true);

        List<String> orgRoleMappings = gaeaUserService.getOrgRoleMappings(username);

        Map<String, Object> result = new HashMap(2);
        result.put("tree", tree);
        result.put("roles", orgRoleMappings);
        return responseSuccessWithData(result);
    }

    @GetMapping("/queryByOrgCode/{orgCode}")
    @Permission(code = "detail", name = "明细")
    public GaeaOrgDTO queryByOrgCode(@PathVariable("orgCode") String orgCode) {
        logger.info("{}根据orgCode查询服务开始，orgCode为：{}", this.getClass().getSimpleName(), orgCode);
        GaeaOrgDTO gaeaOrgDTO = gaeaOrgService.queryByOrgCode(orgCode);
        //对返回值建处理
        detailResultHandler(gaeaOrgDTO);
        resultDtoHandle(gaeaOrgDTO);
        logger.info("{}根据orgcode查询结束，结果：{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(gaeaOrgDTO));
        return gaeaOrgDTO;
    }

    /**
     * 根据ID修改对饮记录，远程跨服务调用
     *
     * @param dto
     * @return
     * @throws Exception
     */
    @PutMapping("/updateNameStatusByCode")
    @Permission(code = "update", name = "更新")
    @GaeaAuditLog(pageTitle = "修改")
    public ResponseBean updateNameStatusByCode(@RequestBody GaeaOrgDTO dto) {
        logger.info("{}更新服务开始, 参数：{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(dto));
        if(dto == null || StringUtils.isBlank(dto.getOrgCode())){
            return this.failure("Field.Blank.Error", "orgCode");
        }
        if(StringUtils.isBlank(dto.getOrgName())){
            return this.failure("Field.Blank.Error", "orgName");
        }
        if(dto.getEnabled() == null){
            return this.failure("Field.Blank.Error", "enable");
        }

        Integer count = gaeaOrgService.updateNameStatusByCode(dto);
        logger.info("{}更新服务结束，结果：{}条", this.getClass().getSimpleName(), count);
        return count!=null && count.intValue()>0 ? this.responseSuccess(): this.failure();
    }


    /**
     * 根据orgCode删除机构
     *
     * @param orgCode
     * @return
     */
    @DeleteMapping("/deleteByOrgCode/{orgCode}")
    @Permission(code = "delete", name = "删除")
    @GaeaAuditLog(pageTitle = "删除")
    public ResponseBean deleteByOrgCode(@PathVariable("orgCode") String orgCode) {
        logger.info("{}删除服务开始，参数orgCode：{}", this.getClass().getSimpleName(), orgCode);
        Integer count = gaeaOrgService.deleteByOrgCode(orgCode);
        logger.info("{}删除服务结束，删除：{}条", this.getClass().getSimpleName(), count);
        return count!=null && count.intValue()>0 ? this.responseSuccess(): this.failure();
    }
}

